<?php

namespace app\api\controller;

use app\admin\model\Image;
use app\admin\model\Product as ProductMdl;

/**
 * 村特产接口
 * @package app\api\controller
 */
class Product extends BaseController
{

    /**
     * 获取产品列表
     *
     * @return \think\response\Json
     */
    public function getProductList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }

        $where = [
            'villageId' => $param->villageId
        ];
        $fields = 'id, title, imgUrl, price, unit';

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $result = ProductMdl::where($where)->order('createDate DESC')->limit($start, $length)->field($fields)->select();
        $total = ProductMdl::where($where)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到村图片');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 获取产品详情
     *
     * @return \think\response\Json
     */
    public function getProductDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->productId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'productId不能这空');
        }

        $productId = $param->productId;
        $where = [
            'id' => $productId
        ];
        $fields = 'title, price, unit, minBuyNum, description';

        $product = ProductMdl::where($where)->order('createDate DESC')->field($fields)->find();
        // 图集
        $imagesList = Image::where(['relatedId' => $productId, 'tag' => 'imglist'])->field('imgUrl')->select();
        $product->imagesList = $imagesList;

        if (empty($product)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关产品');
        } else {
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $product);
        }
    }

}